package io.github.wppli.types.common;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

@Component
public class OssUtil {

    @Value("${oss.url-prefix}")
    private String URL_PREFIX;

    @Value("${oss.endpoint}")
    private String BASE_ENDPOINT;

    @Value("${oss.access-key-id}")
    private String OSS_ACCESS_KEY_ID;

    @Value("${oss.access-key-secret}")
    private String OSS_ACCESS_KEY_SECRET;

    @Value("${oss.bucket.user}")
    private String BUCKET_NAME;

    @Value("${oss.bucket.slideshow}")
    private String BUCKET_NAME_SLIDESHOW;

    public String ossUploadFile(@NotNull String fileName, @NotNull InputStream in) {

        String url = "";

        // 构建日期目录
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String datePath = dateFormat.format(new Date());
        String filePath = datePath + "/" + fileName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(URL_PREFIX + BASE_ENDPOINT, OSS_ACCESS_KEY_ID,OSS_ACCESS_KEY_SECRET);

        try {

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, filePath, in);

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传图片。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // result.getETag(); tag 值是每个文件的唯一标识.

            // 生成 url 地址
            url = URL_PREFIX + BUCKET_NAME + "." + BASE_ENDPOINT + "/" + filePath;

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return url;
    }

    public void ossDeleteFile() {

        String bucketName = "examplebucket";
        String objectName = "exampleobject.txt";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(URL_PREFIX + BASE_ENDPOINT, OSS_ACCESS_KEY_ID,OSS_ACCESS_KEY_SECRET);


        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }


    public String ossUploadFile(@NotNull String fileName, @NotNull InputStream in, String dir) {

        String url = "";

        // 构建日期目录
        String path = dir + "/" + fileName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(URL_PREFIX + BASE_ENDPOINT, OSS_ACCESS_KEY_ID,OSS_ACCESS_KEY_SECRET);
        try {

//            // 判断存储空间是否存在。如果返回值为true，则存储空间存在，如果返回值为false，则存储空间不存在。
//            boolean exists = ossClient.doesBucketExist(BUCKET_NAME);
//            if (!exists) {
//                // 不存在!!
//            }

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME_SLIDESHOW, path, in);

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传图片。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // result.getETag(); tag 值是每个文件的唯一标识.

            // 生成 url 地址
            url = URL_PREFIX + BUCKET_NAME_SLIDESHOW + "." + BASE_ENDPOINT + "/" + path;

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return url;
    }


    public String ossDownloadFile(String filePath) {

        if (!filePath.contains((URL_PREFIX + BUCKET_NAME_SLIDESHOW + "." + BASE_ENDPOINT))) {
            return null;
        }

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(URL_PREFIX + BASE_ENDPOINT, OSS_ACCESS_KEY_ID,OSS_ACCESS_KEY_SECRET);

        try {
            // ossObject包含文件所在的存储空间名称、文件名称、文件元数据以及一个输入流。
            filePath = filePath.substring((URL_PREFIX + BUCKET_NAME_SLIDESHOW + BASE_ENDPOINT).length() + 2);
//            System.out.println(filePath);

            InputStream inputStream = ossClient.getObject(new GetObjectRequest(BUCKET_NAME_SLIDESHOW, filePath)).getObjectContent();

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            IOUtils.copy(inputStream, outputStream);
            byte[] byteArray = outputStream.toByteArray();
            // 将字节数组转为Base64字符串
            // 输出Base64图片
            return Base64.getEncoder().encodeToString(byteArray);

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String url = "https://aigc-user-file.oss-cn-beijing.aliyuncs.com/2024/01/31/737ba2f0-3206-49fd-b3bd-61848da8fd90.jpg";
        url = url.substring(("https://aigc-user-file.oss-cn-beijing.aliyuncs.com").length() + 1);
        System.out.println(url);
    }




}
